import os
import sys
import chardet

def convert(filename , out_enc = 'utf-8'):
  try:
    with open(filename, 'rb') as f:
        content_bytes = f.read()
    # print(type(f))

    source_encoding = chardet.detect(content_bytes).get('encoding')
    # print(chardet.detect(content_bytes))

    with open(filename, 'r', encoding = source_encoding) as f:
        content_str = f.read()
    # print(type(content_str))
    # print(filename)

    with open(filename, 'w', encoding = out_enc) as f:
        f.write(content_str)

    # with open(filename, 'rb') as f:
    #     content_bb = f.read()
    # print(chardet.detect(content_bb))

    # statinfo = os.stat(filename)
    # print(statinfo)

  except IOError as err:
    print("I/O error:{0}".format(err))

def explore(dir):
  count = 0
  for root, dirs, files in os.walk(dir):
    for file in files:
      if file.endswith(".h") or\
        file.endswith(".hpp") or \
        file.endswith(".cpp") or \
        file.endswith(".cc"):
        print(file)
        path = os.path.join(root, file)
        convert(path)
        count += 1
  print("%d files convert." %(count))

if __name__=="__main__":
  dir = '../../'
  explore(dir)

